<template lang="pug">
  .page
    .AccountsReceivableManage
      .search-form.mb-10.pl-10.pr-10
        Form.ivu-row(ref="formData" :model="formData" :rules="rules" :label-width="90")
          FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'select'")
              Select(v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item.securityNO"
                  :key="index"
                ) {{ c_item.securityNO }}
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder")
            template(v-if="item.type === 'interval'")
              DatePicker.pull-left.interval(:value="formData[item.model1]" :placeholder="item.placeholder1" type="month" @on-change="handleChangeDatePicker(item.model1, $event)")
              span.pl-10.pr-10.pull-left.line-h-32 --
              DatePicker.pull-left.interval(:value="formData[item.model2]" :placeholder="item.placeholder2" type="month" @on-change="handleChangeDatePicker(item.model2, $event)")
            template(v-if="item.type === 'button'")
              Button(v-if="hasFind" type="info" @click="searchFn") 查询

      .pl-20.pr-20.bg-white
        Table.hasTitle-table.beautiful-table(:columns="thead" :data="tableData" :stripe="true" ref="demoTable"
          @on-selection-change="handleOnSelectChange"
        )
          .clearfix.pr-24.pl-12.overflow-hidden(slot="header")
            .pull-right.table-title-btns
              Button.mr-10(v-if="hasExport" type="info" @click="exportSocialSecurityBill") 导出
          .clearfix.pl-20.pr-20(slot="footer")
            Page(
              :total="tableComone.totalRows"
              @on-change="onChangePage"
              @on-page-size-change="onpageSizeChange"
              show-sizer
              show-total
              placement="top"
              prev-text="上一页"
              next-text="下一页"
            )
</template>

<script>
import { SocialSecurityPayableBillApi } from '@/api/SocialSecurityPayableBill.api.js'
import { BalanceApi } from '@/api/Balance.api.js'
import { ShouldPayableThead } from './tableHead.js'
import _cloneDeep from 'clone-deep'
import { EmployeesApi } from '@/api/Employees.api.js'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro.replace('/api', '/')

export default {
  name: '',

  components: {
  },

  data () {
    return {
      companyId: '', // 公司ID
      companyName: '', // 公司名称
      employeeId: '', // 员工ID
      thead: _cloneDeep(ShouldPayableThead),
      tableData: [],
      formData: {
        socialSecurityNo: '',
        feeYearMonthStart: new Date(),
        feeYearMonthEnd: new Date()
      },
      formItem: [
        { type: 'select', label: '社保编号：', placeholder: '请输入社保编号', prop: 'socialSecurityNo', model: 'socialSecurityNo', options: 'securityNos', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6' },
        { type: 'interval', label: '费用月份：', placeholder1: '开始日期', prop1: 'feeYearMonthStart', model1: 'feeYearMonthStart', placeholder2: '结束日期', prop2: 'feeYearMonthEnd', model2: 'feeYearMonthEnd', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6' },
        { type: 'button', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6' }
      ],
      rules: {
        IdCardNo: [
          { type: 'string', message: '请输入正确的身份证号码', pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/ }
        ]
      },
      selectedEmployeeId: [], // 勾选的id集合,array格式
      selectedEmployeeArr: [], // 勾选的id, name数组集合
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10, // 当前页面展示条数
        inServiceCount: 0, // 在职
        outServiceCount: 0 // 离职
      },
      downLoadRul: '',
      arrListDown: {
        securityNos: []
      },
      datePickerDefault: new Date(), // 当前时间
      importExcel: {
        uploadLoading: false,
        progressPercent: 0,
        showProgress: false,
        showRemoveFile: false,
        file: null
      }
    }
  },

  watch: {
  },
  computed: {
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 导出
    hasExport () {
      return this.actionArr.indexOf('ExportSocialSecurityBill') > -1
    },
    // 查询
    hasFind () {
      return this.actionArr.indexOf('GetSocialSecurityBalanceList') > -1
    }
  },

  mounted () {
    this.query()
    this.getSecurityNos()
  },

  methods: {
    // 搜索
    searchFn () {
      this.tableComone.pageIndex = 1
      this.query()
    },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (val) {
      this.tableComone.pageIndex = val
      this.query()
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (val) {
      this.tableComone.pageIndex = 1
      this.tableComone.pageSize = val
      this.query()
    },
    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      var params = {
        // HasPaging: true,
        SocialSecurityNo: this.formData.socialSecurityNo,
        FeeYearMonthStart: this.formData.feeYearMonthStart,
        FeeYearMonthEnd: this.formData.feeYearMonthEnd,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize
      }
      let res = await BalanceApi.getSocialSecurityBalanceList(params)
      console.log('社保差额res: ', res)
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data
        this.tableComone.totalRows = res.data.totalRows
        this.tableData.map(item => {
          item.insures.map(i_item => { // 第一层表格中的数据拼接
            item[i_item.insuranceCode + 'balance'] = i_item.balance
            item[i_item.insuranceCode + 'should'] = i_item.should
          })

          // 展开明细中的数据拼接
          item.details.map(d_item => {
            console.log('d_item: ', d_item)
            d_item.insures.map(i_item => { // 第一层表格中的数据拼接
              d_item[i_item.insuranceCode + 'balance'] = i_item.balance
              d_item[i_item.insuranceCode + 'should'] = i_item.should
            })
          })
        })
        // console.log('this.tableData: ', this.tableData)
      } else {
        this.tableData = []
      }
      this.loading = false
    },

    // 获取保险编号
    async getSecurityNos () {
      let res = await SocialSecurityPayableBillApi.getSecurityNos(1)
      console.log('获取保险编号res: ', res)
      if (res.status === 200 && res.data.success) {
        this.arrListDown.securityNos = res.data.data
        // this.$refs.ImportStandingBookModal.arrListDown.securityNos = res.data.data
      } else {
        this.arrListDown.securityNos = []
      }
    },

    // 表格选择操作
    handleOnSelectChange (value) {
      this.selectedEmployeeArr = value.map((item) => {
        return { id: item.id, name: item.name }
      })
      this.selectedEmployeeId = value.map((item) => {
        return item.id
      })
      console.log('列表勾选数组1', this.selectedEmployeeArr)
      console.log('列表勾选数组2', this.selectedEmployeeId)
    },

    // 日期选择
    handleChangeDatePicker (model, val) {
      console.log('model: ', model)
      console.log('val: ', val)
      this.formData[model] = val
    },

    // 导出社保差额账单
    async exportSocialSecurityBill () {
      var params = {
        HasPaging: true,
        SocialSecurityNo: this.formData.socialSecurityNo,
        FeeYearMonthStart: this.formData.feeYearMonthStart,
        FeeYearMonthEnd: this.formData.feeYearMonthEnd,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize
      }
      console.log('params: ', params)
      let res = await BalanceApi.exportSocialSecurityBill(params)
      console.log('导出社保差额账单res: ', res)
      if (res.status === 200 && res.data.success) {
        console.log('❤ 返回链接: ', baseUrl + res.data.message)
        window.open(baseUrl + res.data.message, '_blank')
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 台账导入-显示弹窗
    handleShowImportStandingBookModal () {
      this.$refs.ImportStandingBookModal.isShowImportStandingBookModal = true
      this.$refs.ImportStandingBookModal.arrListDown.securityNos = this.arrListDown.securityNos
      Object.keys(this.$refs.ImportStandingBookModal.formData).forEach(key => {
        this.$refs.ImportStandingBookModal.formData[key] = ''
      })
    }
  } // methods end
}
</script>

<style lang="less" scoped>

</style>
